package com.sinosoft.ci.patch;

import java.io.File;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.sinosoft.ci.patch.yqscm.YQScmFileExtractExcel;
import com.sinosoft.ci.utils.FileSystemUtils;

/**
 * 国联核心程序入口
 * @author 韩朝祥
 *
 */
public class GuoLianLisProgram {
	
	private static final Logger logger = Logger.getLogger(GuoLianLisProgram.class);

	public static void main(String[] args) {
		if(args == null || args.length < 2){
			System.out.println("参数不对！！！！");
			
			System.out.println("第一个参数是清单文件，第二个参数是工程目录！");
			
			System.exit(1);
		}
		
		File excel = new File(args[0]);
		File appRootDir = new File(args[1]);
		String uploadUrl = null;
		String appKey = null;
		if(args.length > 3){
			uploadUrl = args[2];
			appKey = args[3];
			uploadPatchListFile(excel, uploadUrl,appKey);
			System.out.println("由于上传了清单文件，不生成补丁包！");
			return;
		}
		
		String zipName = excel.getName();
		if(zipName.indexOf(".") > 0){
			zipName = zipName.substring(0,zipName.lastIndexOf("."));
		}
		
		YQScmFileExtractExcel e = new YQScmFileExtractExcel(excel, appRootDir);
		String[] patchEntys = e.getPatchEntry();
		
		IncrementPatchGenerator g = new IncrementPatchGenerator(appRootDir, FileSystemUtils.getWorkDir());
		g.extractPatch(patchEntys, zipName + ".zip");
		
		System.out.println("打包成功！");
	}
	
	/**
	 * 上传补丁清单文件
	 */
	private static void uploadPatchListFile(File file,String uploadUrl,String appKey){
		HttpPost post = new HttpPost(uploadUrl);
		MultipartEntityBuilder builder = MultipartEntityBuilder.create();
		builder.addTextBody("appKey", appKey);
		builder.addBinaryBody("patchListFile", file);
		post.setEntity(builder.build());
		
		CloseableHttpClient httpclient = HttpClients.createDefault();
		CloseableHttpResponse res = null;
		try{
			res = httpclient.execute(post);
			HttpEntity entity = res.getEntity();
			String resStr = EntityUtils.toString(entity);
			
			if(200 != res.getStatusLine().getStatusCode()){
				System.out.println("清单文件上传失败！服务器响应码为：" + res.getStatusLine().getStatusCode());
				return;
			}
			if(resStr != null && resStr.contains("200")){
				System.out.println("补丁清单文件上传成功！");
				return;
			}else{
				System.out.println("清单上传失败！服务器响应：" + resStr);
			}
		}catch(Exception ex){
			logger.error("清单文件上传失败！", ex);
		}finally{
			IOUtils.closeQuietly(httpclient);
			IOUtils.closeQuietly(res);
		}
	}
}
